package com.zzc.plugin;

import com.intellij.openapi.project.Project;

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.ArrayList;


public class SettingUi {
    private JPanel mainPanel;
    private Project project;
    private File configFile;
    private File originalFile;
    private ArrayList<SwitchInfo> switchInfoList;
    private boolean isAllSelect = true;

    public SettingUi(Project project, File originalFile, File configFile) {
        this.project = project;
        this.originalFile = originalFile;
        this.configFile = configFile;
        switchInfoList = new ArrayList<>();
        readConfig();
        init();

    }

    private void _readFromFile() {
        switchInfoList.clear();
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(configFile));
            String temp;
            String lastAnn = null;
            int count = 0;
            while ((temp = br.readLine()) != null) {
                if (temp.length() > 0) {
                    if (temp.startsWith("#") || temp.startsWith("//")) {
                        lastAnn = temp.replaceAll("#", "").replaceAll("//", "").replace(" ", "");
                        count++;
                        continue;
                    }
                    SwitchInfo info = new SwitchInfo(temp);
                    if (lastAnn != null && count > 1) {
                        info.setName(lastAnn);
                    }
                    lastAnn = null;
                    if (info.getKey() != null) {
                        if (!switchInfoList.contains(info)) {
                            switchInfoList.add(info);
                        }
                    }
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) br.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void readConfig() {
        if (!configFile.exists()) {
            try {
                configFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (originalFile.exists()) {
                try {
                    copyFileUsingFileStreams(originalFile, configFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                _readFromFile();
            } else {
                switchInfoList.add(new SwitchInfo("忽略kapt任务", Config.KAPT, true));
                switchInfoList.add(new SwitchInfo("源码依赖uikit", Config.UIKIT, false));
                //添加默认项
                saveConfig();
            }
        } else {
            _readFromFile();
        }
    }

    private void saveConfig() {
        try {
            FileWriter fileWriter = new FileWriter(configFile);
            fileWriter.write("#可以在下面添加新的配置项,格式是${key}=${value} \n");
            for (SwitchInfo switchInfo : switchInfoList) {
                if (switchInfo.getName() != null && switchInfo.getName().length() > 0) {
                    if (switchInfo.getName().startsWith("#") || switchInfo.getName().startsWith("//")) {
                        fileWriter.write( switchInfo.getName() + "\n");
                    } else {
                        fileWriter.write("# " + switchInfo.getName() + "\n");
                    }
                }
                fileWriter.write(switchInfo + "\n");
            }
            fileWriter.write("#注意，新增了配置项之后，必须要点击重新读取配置文件，否则会被清空");
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void createUIComponents() {

    }

    private void init() {
        mainPanel.setLayout(new FlowLayout());
        JButton jButton = new JButton("点击重新读配置文件(非.local文件)");
        jButton.addActionListener(e -> {
            if (originalFile.exists()) {
                try {
                    copyFileUsingFileStreams(originalFile, configFile);
                } catch (IOException ee) {
                    ee.printStackTrace();
                }
            }
            _readFromFile();
            Component[] components = mainPanel.getComponents();
            ArrayList<Component> del = new ArrayList<>();
            for (Component value : components) {
                if (value instanceof JCheckBox) {
                    del.add(value);
                }
            }
            for (Component component : del) {
                mainPanel.remove(component);
            }
            mainPanel.updateUI();
            addBoxList();
        });

        mainPanel.add(jButton);
        addBoxList();
        JButton jAll = new JButton("一键全选/反选");
        jAll.addActionListener(e -> {
            isAllSelect = !isAllSelect;
            for (SwitchInfo switchInfo : switchInfoList) {
                switchInfo.setEnable(isAllSelect);
            }
            Component[] components = mainPanel.getComponents();
            for (Component value : components) {
                if (value instanceof JCheckBox) {
                    ((JCheckBox) value).setSelected(isAllSelect);
                }
            }
            mainPanel.updateUI();
            saveConfig();
        });
        mainPanel.add(jAll);

    }

    private void addBoxList() {
        for (SwitchInfo switchInfo : switchInfoList) {
            JCheckBox box = new JCheckBox(switchInfo.getName(), switchInfo.isEnable());
            mainPanel.add(box);
            initChange(box, switchInfo);
        }
    }

    private void initChange(JCheckBox box, SwitchInfo info) {
        box.setSelected(info.isEnable());
        box.addActionListener(e -> {
            info.setEnable(box.isSelected());
            saveConfig();
        });
    }


    public JPanel getMainPanel() {
        return mainPanel;
    }

    private static void copyFileUsingFileStreams(File source, File dest)
            throws IOException {
        InputStream input = null;
        OutputStream output = null;
        try {
            input = new FileInputStream(source);
            output = new FileOutputStream(dest);
            byte[] buf = new byte[1024];
            int bytesRead;
            while ((bytesRead = input.read(buf)) > 0) {
                output.write(buf, 0, bytesRead);
            }
        } finally {
            if (input != null) {
                input.close();
            }
            if (output != null) {
                output.close();
            }
        }
    }
}
